package com.cars.elasticsearch.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cars.elasticsearch.Variable.GlobalVariables;
import com.cars.elasticsearch.config.RabbitMQConfig;
import com.cars.elasticsearch.domain.DO.Course;
import com.cars.elasticsearch.service.CourseService;
import com.cars.elasticsearch.util.elasticSearch.DocumentUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: caoqianfan
 * @date: 2023/10/12 15:25
 */
@Slf4j
@RestController
@RequestMapping("/course")
public class CourseController {

    @Resource
    private CourseService courseService;
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    DocumentUtil documentUtil;

    @GetMapping("/page")
    public ResponseEntity<Page<Course>> findAllPage(@RequestParam("current") Integer current, @RequestParam("PAGE_SIZE") Integer PAGE_SIZE) {
        Page<Course> page = new Page<>(current, PAGE_SIZE);
        return ResponseEntity.ok(courseService.page(page));
    }

    @GetMapping("/list")
    public ResponseEntity<List<Course>> list(@RequestParam(value = "id", required = false) Long id) {
        if (id == null) {
            return ResponseEntity.ok(documentUtil.listDocument(GlobalVariables.INDEX_NAME_COURSE).stream().sorted(Comparator.comparing(Course::getId)).collect(Collectors.toList()));
        }
        Course course = new Course();
        course.setId(id);
        List<Course> courseList = new ArrayList<>();
        courseList.add(documentUtil.getDocument(course, GlobalVariables.INDEX_NAME_COURSE));
        return ResponseEntity.ok(courseList);
    }

    @PostMapping("/save")
    public ResponseEntity<String> save(@RequestBody List<Course> courseList) {
        courseService.saveBatch(courseList);
        rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE, RabbitMQConfig.KEY_COURSE_SAVE, JSON.toJSONString(courseList));
        return ResponseEntity.ok("ok");
    }

    @PutMapping("/update")
    public ResponseEntity<String> update(@RequestBody List<Course> courseList) {
        courseService.updateBatchById(courseList);
        rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE, RabbitMQConfig.KEY_COURSE_SAVE, JSON.toJSONString(courseList));
        return ResponseEntity.ok("ok");
    }

    @DeleteMapping("/delete")
    public ResponseEntity<String> delete(@RequestBody List<Long> idList) {
        courseService.removeBatchByIds(idList);
        rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE, RabbitMQConfig.KEY_COURSE_REMOVE, idList);
        return ResponseEntity.ok("ok");
    }
}